package com.ruoyi.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.customer.AsyncCustomerChange;
import com.ruoyi.customer.SentMessage;
import com.ruoyi.customer.domain.*;
import com.ruoyi.customer.mapper.*;
import com.ruoyi.customer.service.CommonService;
import com.ruoyi.exportCustomer.mapper.ExportLogMapper;
import com.ruoyi.utils.MessageSend;
import com.ruoyi.utils.ModifiedPropertyUtil;
import com.ruoyi.utils.modifiedProperty.ModifiedPropertyInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@RequiredArgsConstructor
@Service
public class CommonServiceImpl implements CommonService {

    private final TotalComsterMapper totalComsterMapper;
    private final CustomerMapper customerMapper;
    private final ExportLogMapper exportLogMapper;
    private final MessageSend messageSend;
    private final CustomerSourceMapper customerSourceMapper;

    private final TCustomerInfoChangeMapper customerInfoChangeMapper;

    private final TCustomerInfoChangeDetailMapper customerInfoChangeDetailMapper;

    @Async
    @EventListener
    public void totalCustomerUpdate(CommonInfo commonInfo) {
        Long id = commonInfo.getId();
        String tel = commonInfo.getTel();
        customerMapper.customerInsert(id);

        LambdaQueryWrapper<TotalComster> totalWrapper = new LambdaQueryWrapper<>();
        totalWrapper.eq(TotalComster::getMobile, tel);
        List<TotalComster> totalComsters = totalComsterMapper.selectList(totalWrapper);
        if (!CollectionUtils.isEmpty(totalComsters)) {
            for (TotalComster totalComster : totalComsters) {
                Customer customer = new Customer();
                customer.setId(id);
                customer.setTotalCustomerId(totalComster.getId());
                customerMapper.updateById(customer);
                totalComster.setCustomerFlag("1");
                totalComster.setDelFlag("0");
                totalComsterMapper.updateById(totalComster);
            }
        }
    }


    @Async
    @EventListener
    public void inertBathTelRecord(TelBathRecord bathRecord) {
        String bathLog = bathRecord.getBathLog();
        String tableName = bathRecord.getTableName();
        if (StringUtils.isNotBlank(tableName) && StringUtils.isNotBlank(bathLog)) {
            exportLogMapper.insertBathLog(tableName, bathLog);

            // 更新客户表批次
            exportLogMapper.updateCustomerBatchLogo();
            // 更新客户表批次
            exportLogMapper.updateTotalCustomerBatchLogo();

            exportLogMapper.insertSource(tableName, "Excel导入");
        }
    }

    @Async
    @EventListener
    public void sentInfo(SentMessage sentMessage) {
        String type = sentMessage.getType();
        List<String> userIds = sentMessage.getUserIds();
        String content = sentMessage.getContent();
        String operationName = sentMessage.getOperationName();
        messageSend.sendNotice(type, content, userIds, operationName);
    }


    @Async
    @EventListener
    public void updateCustomerSource(CustomerSource customerSource) {
        if (customerSource == null) {
            return;
        }
        if (!StringUtils.isNotBlank(customerSource.getSource())) {
            return;
        }
        if (!StringUtils.isNotBlank(customerSource.getTel())) {
            return;
        }
        String tel = customerSource.getTel();
        customerSourceMapper.insertCustomerSource(customerSource);
        customerSourceMapper.updateCustomerSource(tel);
        customerSourceMapper.updateTotalCustomerSource(tel);
    }

    @Override
    public void customerChangeRecord(CustomerChange oldData, String oldDataJson, CustomerChange newData, String newOldJson, Map<String, Object> map, String type) {
        AsyncCustomerChange asyncCustomerChange = new AsyncCustomerChange();
        asyncCustomerChange.setOldCustomerChange(oldData);
        asyncCustomerChange.setNewCustomerChange(newData);
        asyncCustomerChange.setMap(map);
        asyncCustomerChange.setNewDataJson(newOldJson);
        asyncCustomerChange.setOldDataJson(oldDataJson);
        if (Objects.equals("1", type)) {
            changeRecord(asyncCustomerChange);
        } else {
            // 异步执行
            SpringUtils.context().publishEvent(asyncCustomerChange);
        }
    }

    @Async
    @EventListener
    public void changeRecord(AsyncCustomerChange customerChange) {
        String oldDataJson = customerChange.getOldDataJson();
        String newDataJson = customerChange.getNewDataJson();
        CustomerChange oldData = customerChange.getOldCustomerChange();
        CustomerChange newData = customerChange.getNewCustomerChange();
        Map<String, Object> map = customerChange.getMap();
        Long customerId = (Long) map.get("customerId");
        Long createId = (Long) map.get("createId");
        String createBy = (String) map.get("createBy");
        String tel = (String) map.get("tel");
        String type = (String) map.get("type");
        List<ModifiedPropertyInfo> differentProperty = ModifiedPropertyUtil.getDifferentProperty(new CustomerChange(), oldData, newData);
        if (!CollectionUtils.isEmpty(differentProperty)) {
            // 记录信息
            TCustomerInfoChange tCustomerInfoChange = new TCustomerInfoChange();
            tCustomerInfoChange.setCreateId(createId);
            tCustomerInfoChange.setCreateBy(createBy);
            tCustomerInfoChange.setType(type);
            tCustomerInfoChange.setCustomerId(customerId);
            tCustomerInfoChange.setTel(tel);
            tCustomerInfoChange.setAfterInfo(newDataJson);
            tCustomerInfoChange.setBeforeInfo(oldDataJson);
            customerInfoChangeMapper.insert(tCustomerInfoChange);
            Long changeId = tCustomerInfoChange.getId();
            for (ModifiedPropertyInfo modifiedPropertyInfo : differentProperty) {
                String propertyName = modifiedPropertyInfo.getPropertyName();
                String propertyExplain = modifiedPropertyInfo.getPropertyExplain();
                Object oldValue = modifiedPropertyInfo.getOldValue();
                Object newValue = modifiedPropertyInfo.getNewValue();
                TCustomerInfoChangeDetail tCustomerInfoChangeDetail = new TCustomerInfoChangeDetail();
                tCustomerInfoChangeDetail.setCustomerId(customerId);
                tCustomerInfoChangeDetail.setTel(tel);
                tCustomerInfoChangeDetail.setCreateBy(createBy);
                tCustomerInfoChangeDetail.setCreateId(createId);
                tCustomerInfoChangeDetail.setType(type);
                tCustomerInfoChangeDetail.setChangeId(changeId);
                tCustomerInfoChangeDetail.setName(propertyExplain);
                tCustomerInfoChangeDetail.setCode(propertyName);
                if (!Objects.isNull(oldValue)) {
                    tCustomerInfoChangeDetail.setBeforeInfo(String.valueOf(oldValue));
                }
                if (!Objects.isNull(newValue)) {
                    tCustomerInfoChangeDetail.setAfterInfo(String.valueOf(newValue));
                }
                customerInfoChangeDetailMapper.insert(tCustomerInfoChangeDetail);
            }
        }
    }
}
